var fs = require('fs')
var express = require('express')
var router = express.Router()


router.get('/getList',function(req,res){
  if(req){
    console.log('yes')
    fs.readFile('./db.json',function(err,data){
      data = data.toString()
      res.send(data)
    })
  }else{

  }
})
router.get('/getnewslist',function(req,res){
  if(req){
    fs.readFile('./db.json',function(err,data){
      data = data.toString()
      res.send(data)
    })
  }
})
router.get('/getnewsinfo',function(req,res){
  if(req){
    fs.readFile('./db.json',function(err,data){
      data = data.toString()
      res.send(data)
    })
  }
})
router.get('/getcomments',function(req,res){
  if(req){
    fs.readFile('./comments.json',function(err,data){
      data = data.toString()
      res.send(data)
    })
  }
})
router.post('/api/postcomment/:id',function(req,res){
  if(req){
    console.log("hahs")
    console.log(req.body)
    fs.readFile('./comments.json',function(err,data){
      var comment = {
        'username':'匿名用户',
        'addTime':Date.now(),
      }
      // req.body = delete(req.body.id)
      Object.assign(comment,req.body)
      var fileData = JSON.parse(data)

      // console.log(req.params)
      console.log(comment)
      if(comment.its == 1){
        fileData.piccomments[parseInt(req.params.id)-1].content.push(comment)
      }else if(comment.its == 0){
        fileData.comments[parseInt(req.params.id)-1].content.push(comment)
      }
      fileData = JSON.stringify(fileData)
      console.log(fileData)
      fs.writeFile('./comments.json',fileData,function(err){
        console.log('ok了')
        if(err){
          throw err
        }else{
          res.send({"status":200,"message":"成功"})
        }
      })
    })
  }
})
router.get('/home/item',function(req,res){
  if(req){
    fs.readFile('./piclist.json',function(err,data){
      data = data.toString()
      res.send(data)
    })
  }
})
router.get('/home/item/:id',function(req,res){
  if(req){
    // // if(req.body.id == 0){
      
    //   fs.readFile('./piclist.json',function(err,data){
    //     data=data.toString();
    //     var all = []
    //     for(var i =0;i<data.piclist.length;i++){
    //       // all = all.concat(data.piclist[i].neirong)
    //       console.log(data.piclist[i].neirong)
    //     }
    //     console.log(all)
    //   })
    // }else{
      fs.readFile('./piclist.json',function(err,data){
        data = data.toString()
        res.send(data)
      })
    }
})
router.get('/home/picinfo/:id',function(req,res){
  if(req){
    fs.readFile('./piclist.json',function(err,data){
      data = data.toString()
      res.send(data)
    })
  }
})
module.exports = router